import grpc from 'grpc';
import {listModules, asClass} from 'awilix';
import serviceContainer from '../lib/serviceContainer';


const protos = listModules('../../protos/*.proto', {cwd: __dirname});
const rpcImpls = listModules('../app/rpcImplements/*.js', {cwd: __dirname});
const getService = (proto) => {

  const service = proto[Object.keys(proto)[0]];
  if (Object.keys(service).length === 1) {
    return getService(service)
  } else {
    return service;
  }
}

const convert2Cb = (promise) => {
  return (call, callback) => {
    return promise(call.request).then((result) => {
      callback(null, result);
    }).catch(callback)
  }
}

export default (server) => {

  const container = serviceContainer();

  rpcImpls.forEach(m=>{
    const registClass = {};
    registClass[m.name] = asClass(require(m.path).default);
    container.register(registClass);
  });

  protos.forEach(p => {
    const proto = grpc.load(p.path);
    const protoService = getService(proto)[p.name].service;
    const rpcImplClass =container.resolve(p.name.replace('Service', 'Impl')); //rpcImpls.find(impl => impl.name.replace('Impl', '') === p.name.replace('Service', '')).name;

    const serviceImpls = {};

    Object.keys(protoService).forEach(key => serviceImpls[key] = convert2Cb(rpcImplClass[key].bind(rpcImplClass)));

    server.addService(protoService, serviceImpls);

  })
}